import {reqCartList, reqDeleteCartById, reqUpdateCheckedByid} from '@/api';

const state = {
  cartList: [],
};
const mutations = {
  // 购物车数据
  GETCSRTLIST(state,cartList){
    state.cartList = cartList;
  },
};
const actions = {
  // 获取购物车列表的数据
  async getCartList({commit}){
    let result = await reqCartList();
    if(result.code == 200){
      commit("GETCSRTLIST",result.data)
    }
  },

  // 购物车删除
  async deleteCartListBySkuId({commit}, skuId){
    let result = await reqDeleteCartById(skuId)
    if(result.code == 200){
      return 'ok'
    }else{
      return Promise.object(new Error('faile'))
    }
  },

  // 更改购物车商品状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },

  // 删除全部勾选的商品
  deleteAllCheckedCart({dispatch,getters}){
    // context:小仓库  commit:提交mutations修改state  getters(计算属性)  dispatch(派发action) action(当前仓库数据)
    // 获取的全部商品的是一个数组
    let PromiseAll = [];
    // 获取购物车中全部的产品
    getters.cartList.cartInfoList.forEach(item => {
     let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId',item.skuId) : "" ;
     PromiseAll.push(promise)
    });
    // 所有成功才是成功,一个失败则所有都失败
    return Promise.all(PromiseAll)
  },

  // 修改全选状态
  updateAllCartChecked({dispatch,state},isChecked){
    let promiseAll = [];
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById',{ skuId:item.skuId, isChecked });
      promiseAll.push(promise)
     });
     return Promise.all(promiseAll)
  }
};

const getters = {
  cartList(state){
    return state.cartList[0] || {}
  }
};

export default{
  state,
  mutations,
  actions,
  getters
}